package com.ingenieria;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

public class Resultados extends Activity {
	
	String [][] result, data;
	int categoryName;
	String totalpages, totalregister,actualpage;
	int numpag;
	ListView lista;
	ResultadosAdapter adapter;
	public ProgressDialog progressDialog;
	Timer tim;
	Button btback, btnext;
	SharedPreferences preferences;
	SharedPreferences.Editor editor;

	ArrayList<HashMap<String, String>> menuItems;
	static final String KEY_POST = "post";
	static final String KEY_TITULO = "titulo";
	static final String KEY_FECHA = "fecha";
	static final String KEY_DESC_CORTA = "desc_corta";
	static final String KEY_URL_IMAGEN = "url_imagen";

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.resultados);
		
        preferences= getSharedPreferences("Resultados",Context.MODE_PRIVATE);
        editor = preferences.edit();
		
		lista = (ListView) findViewById(R.id.itemsresults);
		btback = (Button) findViewById(R.id.back);
		btnext = (Button) findViewById(R.id.next);
		
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
		  categoryName   = extras.getInt("category");
          new AsyncLoader().execute("actividades");
          
          btnext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
		         
		         editor.putInt("actualpage", Integer.parseInt(actualpage)+1);
		         editor.commit();
		         
		         Intent nextpage = new Intent(Resultados.this, Resultados.class);
		         nextpage.putExtra("category", categoryName);
		         startActivity(nextpage);
		         
			}
          });
          
          btback.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				editor.putInt("actualpage", Integer.parseInt(actualpage) - 1);
		         editor.commit();
		         
		         Intent nextpage = new Intent(Resultados.this, Resultados.class);
		         nextpage.putExtra("category", categoryName);
		         startActivity(nextpage);				
			}
		});
          
          
          

		}
	}
	
	private class AsyncLoader extends AsyncTask<String, String, String>{

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(Resultados.this, "", "Cargando...");
		}
		
		@Override
		protected String doInBackground(String... params) {
			
			numpag = preferences.getInt("actualpage", 1);
			
			String URL = "http://23.23.97.15/ingenieria/conexion.php?format=xml&query=select%20*%20from%20noticia%20where%20id_categoria%20="+categoryName;
			
			Log.i("URL", "http://23.23.97.15/ingenieria/conexion.php?format=xml&query=select%20*%20from%20noticia%20where%20id_categoria%20="+categoryName);
			//result = Utilities.getPlainText("http://23.23.97.15/ingenieria/conexion.php?format=xml&query=select%20*%20from%20noticia%20where%20id_categoria%20="+categoryName);
			//data = Utilities.getText("http://23.23.97.15/ingenieria/conexion.php?format=xml&query=select%20*%20from%20noticia%20where%20id_categoria%20="+categoryName);
	        
			menuItems = new ArrayList<HashMap<String, String>>();
			 
	        XMLParser parser = new XMLParser();
	        String xml = parser.getXmlFromUrl(URL); // getting XML
	        Document doc = parser.getDomElement(xml); // getting DOM element
			
	        NodeList nl = doc.getElementsByTagName(KEY_POST);
	        
	        for (int i = 0; i < nl.getLength(); i++) {
	            // creating new HashMap
	            HashMap<String, String> map = new HashMap<String, String>();
	            Element e = (Element) nl.item(i);
	            // adding each child node to HashMap key => value
	            map.put(KEY_TITULO, parser.getValue(e, KEY_TITULO));
	            map.put(KEY_FECHA, parser.getValue(e, KEY_FECHA));
	            map.put(KEY_DESC_CORTA, parser.getValue(e, KEY_DESC_CORTA));
	            map.put(KEY_URL_IMAGEN, parser.getValue(e, KEY_URL_IMAGEN));

	            // adding HashList to ArrayList
	            menuItems.add(map);
	        }
//			
//			 actualpage = result[2][1] ;
//	         totalpages = result[1][1];
//	         totalregister = result[0][1];
//	         
//			
//	          Log.i("INFO", "actualpage="+actualpage+" totalpages="+totalpages+" totalregister="+totalregister);
			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			
//			if(numpag == Integer.parseInt(totalpages)){
//				btnext.setVisibility(View.INVISIBLE);
//			}else{
//				btnext.setVisibility(View.VISIBLE);
//
//			} 
//				
//			if(numpag == 1){
//				btback.setVisibility(View.INVISIBLE);
//			}else{
//				btback.setVisibility(View.VISIBLE);
//
//			}
//			
			for(int z=0;z<menuItems.size();z++){
				Log.i("menuItems", menuItems.get(z).get("titulo"));

			}
			
			adapter = new ResultadosAdapter(Resultados.this, menuItems);
			
			lista.setAdapter(adapter);
			lista.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
					Intent detalle = new Intent(Resultados.this, Detalle.class);
					//detalle.putExtra("id",data[arg2][0]);  
					detalle.putExtra("categoryName",categoryName);
					startActivity(detalle);
				}
			});
			
	        tim=new Timer();
	        tim.schedule(new TimerTask() {
	                @Override
	                public void run() {
	                        Resultados.this.runOnUiThread(new Runnable() {
	                            public void run() {
	                                        adapter.notifyDataSetChanged();
	                            }
	                        });
	                }
	        }, 0, 2000);
		}
		
	}
	@Override
	public void onBackPressed() {
		Intent backpressed = new Intent(Resultados.this, Ingenieria.class);
		
		editor.putInt("actualpage", 1);
        editor.commit();
		
		startActivity(backpressed);
	}
	
	
}
